package com.heima.behavior.service.impl;

import com.heima.behavior.pojo.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dto.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.threadUtil.ThreadLocalUtil;
import com.heima.utils.common.threadUtil.UserInfo;
import org.checkerframework.checker.units.qual.C;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Resource
    private MongoTemplate mongoTemplate;

    /**
     *
     * @param dto
     * @return
     */
    /**
     * 阅读行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //参数校验
        if(dto==null||dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        UserInfo userInfo = ThreadLocalUtil.get();
        if(userInfo==null&&dto.getEquipmentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //构建符合的查询条件
        Criteria criteria = new Criteria()
                .orOperator(Criteria.where("userId").is(userInfo.getId()),Criteria.where("equipmentId").is(dto.getEquipmentId()))
                .andOperator(Criteria.where("articleId").is(dto.getArticleId()));
        //查询用户的阅读行为
        ApReadBehavior readBehavior = mongoTemplate.findOne(Query.query(criteria), ApReadBehavior.class);
        if(readBehavior!=null){
            //设置用户的阅读时间
            readBehavior.setCount(readBehavior.getCount() + 1);//阅读次数+1
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setReadDuration(dto.getReadDuration());
            //更新数据到mongoDB
            mongoTemplate.save(readBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //用户没有词阅读记录
        readBehavior = new ApReadBehavior();
        readBehavior.setReadDuration(dto.getReadDuration());
        readBehavior.setUpdatedTime(new Date());
        readBehavior.setArticleId(dto.getArticleId());
        readBehavior.setCount(1);
        readBehavior.setCreatedTime(new Date());
        readBehavior.setLoadDuration(dto.getLoadDuration());
        readBehavior.setPercentage(dto.getPercentage());
        readBehavior.setUserId(userInfo.getId().longValue());
        readBehavior.setEquipmentId(dto.getEquipmentId());
        //保存数据到数据库
        mongoTemplate.insert(readBehavior);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
